<template>
  <div class="user-modal">
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleCancel"
      center
      top="5vh"
      width="500px"
    >
    <template v-slot:title>
        <div class="dialog-title">
          <div>{{title}}</div>
          <div v-if="disabled" class="dialog-btn cursor iconfont" :class="[isDialogShow ? 'icon-yanjing': 'icon-biyan']" @click="handleClickDialogIsShow"></div>
        </div>
      </template>
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="120px"
        size="medium"
      >
        <!-- <input
          readonly
          type="text"
          autocomplete="off"
          name="mobile"
          class="cus-input"
        />
        <input
          readonly
          type="password"
          autocomplete="new-password"
          name="password"
          class="cus-input"
        /> -->

        <el-row>
          <el-form-item label="账号" prop="account">
            <el-input
              placeholder="请输入账号名称"
              v-model="editForm.account"
              autocomplete="off"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="密码" prop="password">
            <el-input
              ref="passwordRef1"
              v-show="type === 'text'"
              placeholder="请输入账号密码"
              autocomplete="off"
              :disabled="disabled"
              type="text"
              v-model="editForm.password"
            ></el-input>

            <el-input
              ref="passwordRef2"
              v-show="type === 'password'"
              placeholder="请输入账号密码"
              autocomplete="off"
              :disabled="disabled"
              type="password"
              v-model="editForm.password"
            ></el-input>
          </el-form-item>
        </el-row>
        <!-- <el-row>
            <el-form-item label="昵称" prop="nickName">
              <el-input placeholder="请输入昵称" v-model="editForm.nickName" autocomplete="off"></el-input>
            </el-form-item>
          </el-row> -->

        <el-row>
          <el-form-item label="姓名" prop="userName" class="name-box">
            <!-- <el-select
              style="width: 90%"
              v-model="editForm.userName"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="nameLoading"
            >
              <el-option
                v-for="item in nameOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-button
              icon="el-icon-search"
              circle
              @click="nameFocus"
            ></el-button> -->
            <el-input
              ref="deptInput"
              placeholder="请选择姓名"
              @focus="nameFocus"
              v-model="editForm.userName"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
        </el-row>

        <!-- <el-row>
            <el-form-item label="邮箱" prop="email">
              <el-input placeholder="请输入邮箱" v-model="editForm.email"></el-input>
            </el-form-item>
          </el-row> -->

        <el-row>
          <el-form-item label="手机号" prop="mobile">
            <el-input
              placeholder="请输入手机号"
              v-model="editForm.mobile"
              autocomplete="off"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="学籍号/工号" prop="employeeNo">
            <el-input
              placeholder="请输入学籍号/工号"
              v-model="editForm.employeeNo"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
        </el-row>

        <!-- <input type="text" autocomplete="off" name="mobile" style="position: absolute;left: -10000px;">
          <input type="password" autocomplete="new-password" name="password" style="position: absolute;left: -10000px;"> -->

        <!-- <el-row>
            <el-form-item label="性别" prop="sex">
              <el-select style="width: 100%" v-model="editForm.sex" placeholder="请选择性别">
                <el-option v-for="item in sexList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-row> -->

        <!-- <el-row>
            <el-form-item label="年龄" prop="age">
              <el-input placeholder="请输入年龄" v-model="editForm.age" autocomplete="off"></el-input>
            </el-form-item>
          </el-row> -->

        <!-- <el-row>
            <el-form-item label="证件类型" prop="idType">
              <el-select style="width: 100%" v-model="editForm.idType" placeholder="请选择证件类型">
                <el-option v-for="item in idTypeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-row> -->
        <el-row>
          <!-- <el-form-item
            label="证件号码"
            prop="idcardNo"
            v-if="editForm.idType === 0"
          > -->
          <el-form-item label="证件号码" prop="idcardNo">
            <Acc-desensitization
              v-if="dialogVisible"
              ref="AccDesensitization"
              :isdesensitization='editForm.idcardNo.length === 18'
              v-model="editForm.idcardNo"
              :disabled='disabled'
            ></Acc-desensitization>
          </el-form-item>
          <!-- <el-form-item label="证件号码" prop="idcardNo" v-else>
            <el-input
              placeholder="请输入其他"
              v-model="editForm.idcardNo"
            ></el-input>
          </el-form-item> -->
        </el-row>
        <el-row v-if="userShow">
          <el-form-item label="角色" prop="roleNos">
            <el-select
              style="width: 100%"
              v-model="editForm.roleNos"
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in roleList"
                :key="item.roleNo"
                :label="item.roleName"
                :value="item.roleNo"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!-- <el-row v-if="userShow">
            <el-form-item label="部门" prop="deptName" >
              <el-input
                ref="deptInput"
                placeholder="请选择部门"
                @focus="deptFocus"
                v-model="editForm.deptName"
              ></el-input>
            </el-form-item>
          </el-row> -->
        <!-- <el-row v-if="userShow">
            <el-form-item label="岗位" prop="positionId" >
              <el-select style="width: 100%" v-model="editForm.positionId" placeholder="请选择岗位">
                <el-option
                  v-for="item in positionList"
                  :key="item.positionId"
                  :label="item.positionName"
                  :value="item.positionId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-row> -->

        <!-- <el-row>
            <el-form-item label="员工卡号" prop="employeeCardNo" >
              <el-input placeholder="请输入员工卡号" v-model="editForm.employeeCardNo"></el-input>
            </el-form-item>
          </el-row> -->
        <!-- <el-row>
            <el-form-item label="用户类型" prop="userType" >
              <el-select style="width: 100%" v-model="editForm.userType" multiple placeholder="请选择用户类型">
                <el-option
                  v-for="item in userTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-row> -->
        <el-row>
          <el-form-item label="用户状态" prop="isEnable">
            <el-radio-group v-model="editForm.isEnable">
              <el-radio :label="1">账号可用</el-radio>
              <el-radio :label="0">不可用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <!-- <el-row v-if="userType === '1'">
            <el-form-item label="所属租户" prop="tenantNo">
              <el-select style="width: 100%" v-model="editForm.tenantNo" placeholder="请选择所属租户">
                <el-option
                  v-for="item in tenantList"
                  :key="item.tenantNo"
                  :label="item.tenantName"
                  :value="item.tenantNo"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-row> -->
        <!-- <el-row>
            <el-form-item v-if="model.userNo" label="微信昵称" prop="wxNickName">
              <el-input disabled placeholder="请输入微信昵称" v-model="editForm.wxNickName"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item v-if="model.userNo" label="微信openId" prop="wxOpenId">
              <el-input disabled placeholder="请输入微信openId" v-model="editForm.wxOpenId"></el-input>
            </el-form-item>
          </el-row> -->

        <!-- <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input
              placeholder="请输入备注"
              type="textarea"
              v-model="editForm.remark"
              :maxlength="100"
              :autosize="{ minRows: 4, maxRows: 6 }"
            ></el-input>
          </el-form-item>
        </el-row> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel" size="small">取 消</el-button>
        <el-button type="primary" @click="handleOk('editFormRef')" size="small"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <dept-tree-modal
      ref="deptModal"
      :checkDeptInfo="checkDeptInfo"
      @deptModalOk="deptModalOk"
    ></dept-tree-modal>

    <user-name-modal
      ref="userNameModal"
      :userNameOK="userNameOK"
    ></user-name-modal>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import { addUser, modifyUser, getTenantList } from '../js/auth'
import DeptTreeModal from './DeptTreeModal'
import UserNameModal from './UserNameModal'
import { mapState } from 'vuex'
import {
  // validatePassword,
  validEmail
  // validChinese
  // validEnAndCh
} from '../js/validate'
import { sexList, idTypeList, userTypeList } from '../js/constants'
import md5 from 'md5'
import { encrypt } from '@/utils/crypto'
export default {
  name: 'UserModal',
  components: { DeptTreeModal, UserNameModal },
  data () {
    return {
      isDialogShow: true,
      nameLoading: false,
      nameOptions: [],
      type: 'text',
      title: '',
      dialogVisible: false,
      isAdd: false,
      model: {},
      disabled: false, // 表单项的状态
      userShow: false,
      editForm: {
        account: '',
        nickName: '',
        userName: '',
        mobile: '',
        email: '',
        password: '',
        sex: '',
        age: '',
        roleNos: '',
        deptName: '',
        positionId: '',
        tenantNo: '',
        isEnable: '',
        employeeNo: '',
        employeeCardNo: '',
        idType: '',
        idcardNo: '',
        userType: [],
        remark: ''
      },
      rules: {
        account: [
          // { required: true, validator: validEnAndCh, trigger: "change" },
          { required: true, message: '请输入账号名称！', trigger: ['blur', 'change'] }
        ],
        userName: [{ required: true, message: '请选择姓名！', trigger: 'change' }],
        mobile: [
          {
            required: true,
            validator: this.validatorPhone,
            trigger: ['blur', 'change']
          }
        ],
        email: [{ required: true, validator: validEmail, trigger: 'blur' }],
        password: [
          {
            required: true,
            validator: this.validatePassword,
            trigger: 'change'
          }
        ],
        idcardNo: [{ required: true, validator: this.validatorId }],
        roleNos: [
          { required: true, message: '请选择角色!', trigger: 'change' }
        ],
        deptName: [
          { required: true, message: '请选择部门!', trigger: 'change' }
        ],
        positionId: [
          { required: true, message: '请选择岗位!', trigger: 'change' }
        ],
        tenantNo: [
          { required: true, message: '请选择所属租户!', trigger: 'change' }
        ],
        userType: [
          { required: true, message: '请选择用户类型!', trigger: 'blur' }
        ],
        employeeNo: [
          { required: true, message: '请输入学籍号/工号!', trigger: 'blur' }
        ],
        employeeCardNo: [
          { required: true, message: '请输入员工卡号!', trigger: 'blur' }
        ],
        isEnable: [
          { required: true, message: '请选择状态!', trigger: 'change' }
        ]
      },
      checkDeptInfo: {
        deptId: '',
        deptName: ''
      },
      sexList,
      idTypeList,
      userTypeList,
      tenantList: [],
      userType: JSON.parse(this.$base.getLocalStorage('User-Info')).userType,
      tenantNo: JSON.parse(this.$base.getLocalStorage('User-Info')).tenantNo
    }
  },
  watch: {
    // 校验规则替换
    disabled (val) {
      const {
        rules: { password }
      } = this
      if (val) {
        // password[0].required = false;
        password[0].validator = ''
      } else {
        // password[0].required = true;
        password[0].validator = this.validatePassword
      }
    },
    userType: {
      handler (val) {
        if (val === '1') {
          this.userTypeList.forEach((item) => {
            if (item.value !== '2') this.$set(item, 'disabled', true)
          })
        } else if (val === '2') {
          this.userTypeList.forEach((item) => {
            if (item.value === '1' || item.value === '2') {
              this.$set(item, 'disabled', true)
            }
          })
        }
      },
      immediate: true
    },
    'editForm.password' (val) {
      if (val) {
        this.type = 'password'
        this.$nextTick(() => {
          this.$refs.passwordRef1.blur()
          this.$refs.passwordRef2.focus()
        })
      } else {
        this.type = 'text'
        this.$nextTick(() => {
          this.$refs.passwordRef1.focus()
          this.$refs.passwordRef2.blur()
        })
      }
    }
  },
  computed: {
    ...mapState({
      roleList: (state) => state.auth.roleList,
      positionList: (state) => state.auth.positionList
    })
  },
  mounted () {
    // this.getTenantList()
  },
  methods: {
    handleClickDialogIsShow () {
      this.isDialogShow = !this.isDialogShow
      this.$refs.AccDesensitization.doShow()
    },
    validatePassword (rule, value, callback) {
      if (value === undefined || value === '') {
        callback(new Error('密码不能为空'))
      } else {
        const reg = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{8,20}$/
        // const reg = /^(?![^a-zA-Z]+$)(?!\D+$)(?![a-zA-Z0-9]+$).{8,16}$/
        if (value.indexOf(' ') >= 0) {
          callback(new Error('不能包含空格'))
        } else if (!reg.test(value)) {
          callback(new Error('密码由8-20位数字、字母和特殊符号组成!'))
        } else {
          callback()
        }
      }
    },

    // 身份证号
    validatorId (rule, value, callback) {
      if (value === undefined || value === '') {
        callback(new Error('证件号不能为空'))
      } else {
        callback()
      }
      // else if (/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
      //   // callback(new Error('证件号格式错误'))
      //   // 身份证校验通过
      //   callback()
      // } else if (/^([A-Z]\d{6,10}(\(\w{1}\))?)$/.test(value)) {
      //   // 港澳身份证校验通过
      //   callback()
      // } else if(/^([a-zA-z]|[0-9]){5,17}$/.test(value)) {
      //   // 护照校验通过
      //   callback()
      // } else if (/^[\u4E00-\u9FA5](字第)([0-9a-zA-Z]{4,8})(号?)$/.test(value)) {
      //   // 军官证校验通过
      //   callback()
      // } else if (/^\d{8}|^[a-zA-Z0-9]{10}|^\d{18}$/.test(value)) {
      //   // 台湾身份证
      //   callback()
      // }
    },
    // 校验手机号
    validatorPhone (rule, value, callback) {
      if (value === undefined || value === '') {
        callback(new Error('手机号不能为空'))
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    },

    userNameOK (val) {
      this.editForm.userName = val.name
      this.editForm.userType = val.userType
      this.editForm.tenantNo = val.schoolNo
      this.editForm.personId = val.id

      this.editForm.mobile = val.contact

      if (val.number) {
        this.editForm.employeeNo = val.number
      } else if (val.code) {
        this.editForm.employeeNo = val.code
      } else {
        this.editForm.employeeNo = ''
      }
      this.editForm.idType = val.cardType
      this.editForm.idcardNo = val.idCard
    },

    // 联想词查询
    // remoteMethod (query) {
    //   if (query !== '') {
    //     this.loading = true
    //     setTimeout(() => {
    //       this.loading = false
    //       this.nameOptions = [
    //         'Alabama',
    //         'Alaska',
    //         'Arizona',
    //         'Arkansas',
    //         'California',
    //         'Colorado',
    //         'Connecticut',
    //         'Delaware',
    //         'Florida',
    //         'Georgia',
    //         'Hawaii',
    //         'Idaho',
    //         'Illinois',
    //         'Indiana',
    //         'Iowa',
    //         'Kansas',
    //         'Kentucky',
    //         'Louisiana',
    //         'Maine',
    //         'Maryland',
    //         'Massachusetts',
    //         'Michigan',
    //         'Minnesota',
    //         'Mississippi',
    //         'Missouri',
    //         'Montana',
    //         'Nebraska',
    //         'Nevada',
    //         'New Hampshire',
    //         'New Jersey',
    //         'New Mexico',
    //         'New York',
    //         'North Carolina',
    //         'North Dakota',
    //         'Ohio',
    //         'Oklahoma',
    //         'Oregon',
    //         'Pennsylvania',
    //         'Rhode Island',
    //         'South Carolina',
    //         'South Dakota',
    //         'Tennessee',
    //         'Texas',
    //         'Utah',
    //         'Vermont',
    //         'Virginia',
    //         'Washington',
    //         'West Virginia',
    //         'Wisconsin',
    //         'Wyoming'
    //       ]
    //         .map((item) => {
    //           return { value: `value:${item}`, label: `label:${item}` }
    //         })
    //         .filter((item) => {
    //           return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
    //         })
    //     }, 200)
    //   } else {
    //     this.nameOptions = []
    //   }
    // },

    validateIdcardNo (rule, value, callback) {
      if (value) {
        let reg =
          /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
        if (value.length > 18) {
          callback(new Error('身份证号码不能超过18位!'))
        } else if (!reg.test(value)) {
          callback(new Error('请输入正确的身份证号码!'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },

    // 新增
    add () {
      this.edit({})
    },

    // 编辑
    edit (record) {
      // record.positionId = Number(record.positionId)

      this.model = Object.assign({}, record)
      if (record.userNo) {
        this.disabled = true
        // let ids = []
        const { userRoleList, deptId, deptName, userType } = record
        this.checkDeptInfo = {
          deptId,
          deptName
        }
        // userRoleList.forEach((item) => {
        //   ids.push(item.roleNo)
        // })

        this.$nextTick(() => {
          // this.editForm.roleNos = ids
          if (userRoleList[0] && userRoleList[0].roleNo) {
            this.editForm.roleNos = userRoleList[0].roleNo
          } else {
            this.editForm.roleNos = ''
          }

          this.editForm.userType = userType.split(',')
          // this.userType登录用户类型
          if (this.userType === '1') {
            this.userShow = false
          } else {
            // record.userType添加修改用户类型
            if ((record.userType === '1', record.userType === '2')) {
              this.userShow = false
            } else {
              this.userShow = true
            }
          }
          this.editForm = Object.assign(
            this.editForm,
            pick(
              this.model,
              'account',
              'nickName',
              'userName',
              'email',
              'mobile',
              'password',
              'sex',
              'age',
              'deptName',
              'positionId',
              'tenantNo',
              'idType',
              'idcardNo',
              'isEnable',
              'employeeNo',
              'employeeCardNo',
              'remark',
              'wxNickName',
              'wxOpenId'
            )
          )
        })
      } else {
        if (this.userType === '1') {
          this.userShow = false
        } else {
          this.userShow = true
        }
      }
      this.$nextTick(() => {
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.editFormRef.clearValidate('password')
        })
      })
    },

    // 提交表单
    handleOk (editFormRef) {
      this.$refs[editFormRef].validate(async (valid) => {
        if (valid) {
          let pMd5 =
            this.$base.randomString(3) +
            md5(this.editForm.password) +
            this.$base.randomString(3)

          // const values = {
          //   ...this.editForm,
          //   userType: this.editForm.userType.join(","),
          //   roleNos:
          //     Object.prototype.toString.call(this.editForm.roleNos) ===
          //     "[object String]"
          //       ? [this.editForm.roleNos]
          //       : this.editForm.roleNos,
          //   deptId: this.checkDeptInfo.deptId,
          //   tenantNo:
          //     this.userType === 1 ? this.editForm.tenantNo : this.tenantNo,
          //   password: this.model.userNo ? undefined : pMd5,
          // };

          let values = {
            account: this.editForm.account,
            employeeNo: this.editForm.employeeNo,
            idType: this.editForm.idType,
            idcardNo: this.editForm.idcardNo,
            isEnable: this.editForm.isEnable,
            mobile: this.editForm.mobile,
            password: this.model.userNo ? undefined : pMd5,
            personId: this.editForm.personId,
            roleNos:
              Object.prototype.toString.call(this.editForm.roleNos) ===
                '[object String]'
                ? [this.editForm.roleNos]
                : this.editForm.roleNos,
            tenantNo: this.editForm.tenantNo,
            userName: this.editForm.userName,
            userType: this.editForm.userType.join(',')
          }

          let res, msg, temp
          if (!this.model.userNo) {
            res = await addUser({ encryptParam: encrypt(values) })
            msg = '保存成功！'
          } else {
            temp = Object.assign({}, values, { userNo: this.model.userNo })
            res = await modifyUser(
              { encryptParam: encrypt(temp) }
            )
            msg = '修改成功！'
          }
          if (res.code === 0) {
            this.$message.success(msg)
          } else {
            this.$message.warning(res.msg)
          }
          this.$emit('ok')
          this.handleCancel()
        }
      })
    },

    // 获取租户列表
    async getTenantList () {
      const { code, data, msg } = await getTenantList()
      if (code === 0) {
        this.tenantList = data
      } else {
        this.$message.warning(msg)
      }
    },

    // 上级部门弹框回调
    deptModalOk (val) {
      this.checkDeptInfo = val
      this.editForm.deptName = val.deptName
    },

    // 部门获取焦点弹框
    deptFocus () {
      this.$refs.deptModal.add()
      this.$refs.deptInput.blur()
    },

    // 姓名获取焦点弹框
    nameFocus () {
      this.$refs.userNameModal.openModal()
    },

    // 取消
    handleCancel () {
      this.disabled = false
      this.dialogVisible = false
      this.$refs.editFormRef.resetFields()
      this.editForm = {
        account: '',
        nickName: '',
        userName: '',
        mobile: '',
        email: '',
        password: '',
        sex: '',
        age: '',
        roleNos: '',
        deptName: '',
        positionId: '',
        tenantNo: '',
        isEnable: '',
        employeeNo: '',
        employeeCardNo: '',
        idType: '',
        idcardNo: '',
        userType: [],
        remark: ''
      }
      this.checkDeptInfo = {}
    }
  }
}
</script>

<style lang="scss" scoped>
.user-modal {
  .el-form-item {
    margin-bottom: 30px;
  }

  /deep/ .name-box {
    .el-form-item__content {
      display: flex;
    }
  }
  .dialog-title{
    display: flex;
    justify-content: space-between;
    margin-right: 25px;
    .dialog-btn {
      font-size: 18px;
    }
  }
  // .userFormItem {
  //   margin-bottom: 17px;
  // }
  // .cus-input {
  //   position: absolute;
  //   left: -10000px;
  // }
}
</style>
